<template>
	<view class="order-confirm-container">
		<!-- 商品列表 -->
		<view class="goods-section">
			<view class="section-title">商品信息</view>
			<view class="goods-list">
				<view v-for="(item, index) in orderData.items" :key="index" class="goods-item">
					<image :src="item.product_image_url" class="goods-image" mode="aspectFill"></image>
					<view class="goods-info">
						<text class="goods-name">{{ item.product_name }}</text>
						<view class="goods-price-qty">
							<text class="goods-price">¥{{ item.price.toFixed(2) }}</text>
							<text class="goods-qty">x{{ item.quantity }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 收货地址 -->
		<view class="address-section">
			<view class="section-title">收货地址</view>
			<view v-if="selectedAddress" class="address-selected" @click="selectAddress">
				<view class="address-header">
					<text class="recipient-name">{{ selectedAddress.recipient_name }}</text>
					<text class="phone-number">{{ selectedAddress.phone_number }}</text>
					<view v-if="selectedAddress.is_default" class="default-tag">默认</view>
				</view>
				<view class="address-detail">
					{{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }} {{ selectedAddress.detailed_address }}
				</view>
				<text class="change-address">点击更换地址 ></text>
			</view>
			<view v-else class="address-empty" @click="selectAddress">
				<image src="/static/images/icon-address.png" class="address-icon"></image>
				<text class="address-empty-text">选择收货地址</text>
				<text class="address-arrow">></text>
			</view>
		</view>

		<!-- 联系方式 -->
		<view class="contact-section">
			<view class="section-title">联系方式</view>
			<view class="contact-input-group">
				<input
					v-model="contactInfo.name"
					class="contact-input"
					placeholder="请输入您的姓名"
					maxlength="20"
				/>
				<input
					v-model="contactInfo.phone"
					class="contact-input"
					placeholder="请输入您的手机号"
					type="number"
					maxlength="11"
				/>
			</view>
		</view>

		<!-- 支付方式 -->
		<view class="payment-section">
			<view class="section-title">支付方式</view>
			<view class="payment-option selected">
				<image src="/static/images/wechat-pay.png" class="payment-icon"></image>
				<text class="payment-name">微信支付</text>
				<text class="payment-check">✓</text>
			</view>
		</view>

		<!-- 备注 -->
		<view class="note-section">
			<view class="section-title">订单备注</view>
			<textarea 
				v-model="customerNotes" 
				class="note-input" 
				placeholder="选填，请输入您的需求或备注信息"
				maxlength="200"
			></textarea>
		</view>

		<!-- 价格明细 -->
		<view class="price-detail">
			<view class="price-row total-row">
				<text class="price-label">订单总价</text>
				<text class="price-value total-price">¥{{ orderData.total_amount.toFixed(2) }}</text>
			</view>
		</view>

		<!-- 提交订单按钮 -->
		<view class="submit-section">
			<button class="submit-btn" @click="submitOrder" :disabled="submitting">
				{{ submitting ? '提交中...' : `提交订单 ¥${orderData.total_amount.toFixed(2)}` }}
			</button>
		</view>
	</view>
</template>

<script>
import { get, post, showLoading, hideLoading } from '@/utils/request.js'
import CartManager from '@/utils/cart.js'

export default {
	data() {
		return {
			orderData: {
				items: [],
				total_amount: 0
			},
			selectedAddress: null, // 选中的收货地址
			contactInfo: {
				name: '',
				phone: ''
			},
			customerNotes: '',
			submitting: false
		}
	},
	onLoad(options) {
		// 获取从购物车传递过来的订单数据
		if (options.data) {
			try {
				this.orderData = JSON.parse(decodeURIComponent(options.data));
			} catch (error) {
				console.error('解析订单数据失败:', error);
				uni.showToast({
					title: '订单数据异常',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
				return;
			}
		}

		// 加载默认地址
		this.loadDefaultAddress();
	},
	onShow() {
		// 页面显示时刷新地址信息（从地址选择页面返回时）
		if (this.selectedAddress) {
			this.loadDefaultAddress();
		}
	},
	methods: {
		// 加载默认地址
		async loadDefaultAddress() {
			try {
				const token = uni.getStorageSync('mp_token');
				if (!token) return; // 未登录则不加载地址

				const res = await get('/addresses/default/info');
				this.selectedAddress = res.data;
				console.log('加载到默认地址:', this.selectedAddress);
			} catch (error) {
				console.log('没有默认地址或加载失败:', error.message);
				// 没有默认地址是正常情况，不显示错误
				if (error.message && !error.message.includes('未设置默认地址')) {
					console.error('加载默认地址失败:', error);
				}
			}
		},

		// 选择收货地址
		selectAddress() {
			uni.navigateTo({
				url: `/pages/address/list?select=true&selectedId=${this.selectedAddress?.id || ''}`
			});
		},

		// 地址选择回调（从地址列表页面返回时调用）
		onAddressSelected(address) {
			this.selectedAddress = address;
		},

		// 提交订单
		async submitOrder() {
			if (this.submitting) return;

			// 检查用户是否已登录
			const token = uni.getStorageSync('mp_token');
			if (!token) {
				uni.showModal({
					title: '需要登录',
					content: '请先登录后再下单',
					showCancel: true,
					cancelText: '取消',
					confirmText: '去登录',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/profile/profile'
							});
						}
					}
				});
				return;
			}

			// 验证收货地址
			console.log('提交订单时的收货地址:', this.selectedAddress);
			if (!this.selectedAddress) {
				uni.showToast({
					title: '请选择收货地址',
					icon: 'none'
				});
				return;
			}

			// 验证联系信息
			if (!this.contactInfo.name.trim()) {
				uni.showToast({
					title: '请输入您的姓名',
					icon: 'none'
				});
				return;
			}

			if (!this.contactInfo.phone.trim()) {
				uni.showToast({
					title: '请输入您的手机号',
					icon: 'none'
				});
				return;
			}

			// 验证手机号格式
			const phoneRegex = /^1[3-9]\d{9}$/;
			if (!phoneRegex.test(this.contactInfo.phone.trim())) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
				return;
			}

			try {
				this.submitting = true;
				showLoading('创建订单中...');

				// 创建订单
				const orderData = {
					items: this.orderData.items,
					contact_name: this.contactInfo.name.trim(),
					contact_phone: this.contactInfo.phone.trim(),
					customer_notes: this.customerNotes,
					shipping_address: {
						recipient_name: this.selectedAddress.recipient_name,
						phone_number: this.selectedAddress.phone_number,
						province: this.selectedAddress.province,
						city: this.selectedAddress.city,
						district: this.selectedAddress.district,
						detailed_address: this.selectedAddress.detailed_address
					}
				};
				console.log('发送的订单数据:', orderData);
				const orderRes = await post('/miniapp/orders', orderData);

				hideLoading();

				// 清空购物车中已下单的商品
				for (const item of this.orderData.items) {
					CartManager.removeFromCart(item.product_id);
				}

				// 跳转到支付页面
				uni.redirectTo({
					url: `/pages/order/payment?orderId=${orderRes.data.order_id}&orderNumber=${orderRes.data.order_number}&amount=${orderRes.data.payment_amount}`
				});

			} catch (error) {
				console.error('创建订单失败:', error);
				uni.showToast({
					title: error.message || '创建订单失败',
					icon: 'none'
				});
			} finally {
				this.submitting = false;
				hideLoading();
			}
		}
	}
}
</script>

<style scoped>
.order-confirm-container {
	background-color: #F5F5F5;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.contact-section {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
}

.contact-input-group {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.contact-input {
	padding: 24rpx;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333333;
	background-color: #FAFAFA;
}

.contact-input:focus {
	border-color: #D4AF37;
	background-color: #FFFFFF;
}

.goods-section, .address-section, .contact-section, .payment-section, .note-section {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 20rpx;
}

.goods-list {
	gap: 20rpx;
}

.goods-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #F0F0F0;
}

.goods-item:last-child {
	border-bottom: none;
}

.goods-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
}

.goods-info {
	flex: 1;
}

.goods-name {
	font-size: 28rpx;
	color: #333333;
	margin-bottom: 12rpx;
	display: block;
}

.goods-price-qty {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.goods-price {
	font-size: 32rpx;
	color: #D4AF37;
	font-weight: bold;
}

.goods-qty {
	font-size: 28rpx;
	color: #666666;
}

.delivery-option, .payment-option {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
}

.delivery-name, .payment-name {
	font-size: 28rpx;
	color: #333333;
}

.delivery-fee {
	font-size: 28rpx;
	color: #D4AF37;
	font-weight: bold;
}

.payment-option {
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	padding: 20rpx;
}

.payment-option.selected {
	border-color: #D4AF37;
	background-color: #FFF9E6;
}

.payment-icon {
	width: 48rpx;
	height: 48rpx;
	margin-right: 16rpx;
}

.payment-check {
	color: #D4AF37;
	font-size: 32rpx;
	font-weight: bold;
}

.note-input {
	width: 100%;
	min-height: 120rpx;
	padding: 20rpx;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333333;
	background-color: #FAFAFA;
}

.price-detail {
	background-color: #FFFFFF;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
}

.price-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16rpx;
}

.price-row:last-child {
	margin-bottom: 0;
}

.price-label {
	font-size: 28rpx;
	color: #666666;
}

.price-value {
	font-size: 28rpx;
	color: #333333;
}

.total-row .price-label {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.total-price {
	font-size: 36rpx;
	font-weight: bold;
	color: #D4AF37;
}

.submit-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #FFFFFF;
	padding: 20rpx 40rpx 40rpx;
	box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.submit-btn {
	width: 100%;
	background-color: #D4AF37;
	color: #FFFFFF;
	border: none;
	border-radius: 50rpx;
	padding: 30rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.submit-btn:disabled {
	background-color: #CCCCCC;
}

.submit-btn:active:not(:disabled) {
	background-color: #B8941F;
}

/* 地址选择相关样式 */
.address-selected {
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	padding: 24rpx;
	position: relative;
}

.address-selected .address-header {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.address-selected .recipient-name {
	font-size: 30rpx;
	font-weight: bold;
	color: #333333;
	margin-right: 20rpx;
}

.address-selected .phone-number {
	font-size: 28rpx;
	color: #666666;
	margin-right: 20rpx;
}

.address-selected .default-tag {
	background-color: #D4AF37;
	color: #FFFFFF;
	font-size: 20rpx;
	padding: 4rpx 12rpx;
	border-radius: 8rpx;
}

.address-selected .address-detail {
	font-size: 26rpx;
	color: #666666;
	line-height: 1.4;
	margin-bottom: 12rpx;
}

.address-selected .change-address {
	font-size: 24rpx;
	color: #D4AF37;
	position: absolute;
	right: 24rpx;
	bottom: 24rpx;
}

.address-empty {
	display: flex;
	align-items: center;
	justify-content: space-between;
	border: 2rpx solid #E0E0E0;
	border-radius: 12rpx;
	padding: 24rpx;
	border-style: dashed;
}

.address-empty .address-icon {
	width: 48rpx;
	height: 48rpx;
	margin-right: 16rpx;
}

.address-empty .address-empty-text {
	flex: 1;
	font-size: 28rpx;
	color: #999999;
}

.address-empty .address-arrow {
	font-size: 24rpx;
	color: #999999;
}
</style>
